<?php

namespace app\batch;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\models\{User as Users, ContractList, ContractOrder, ContractReser, ContractSell};
use think\Db;
use app\facade\Redis;

class Matchorder extends Command
{
    protected function configure()
    {
        $this->setName('Matchorder')->setDescription('合约匹配');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        $cmd = "ps aux | grep '/www/server/php/72/bin/php /www/wwwroot/rskj/think Matchorder'|grep -v 'grep'| awk '{print $2}'";
        exec($cmd, $ps, $ret);
        if (count($ps) > 1) {
            die("batch of  is running");
        }
        ini_set('max_execution_time', 0);
        $list = (new ContractList())->select();
        foreach ($list as $lists) {
            if (time() < (strtotime($lists['start_time']) + 10)) {
                echo '没到时间....';
                continue;
            }
            if (time() >= strtotime($lists['end_time'])) {
                //所有预约抢购订单
                $timess = date('Y-m-d H:i:s', (strtotime($lists['end_time'])));
                $orderlist = (new ContractReser())->order('bixu desc')->where(['cate_id' => $lists['id'], 'status' => 1])->where('created', '<=', $timess)->select();
                Db::startTrans();
                try {
                    //所有预约之前的订单抢购订单做失败处理
                    foreach ($orderlist as $orderlists) {
                        $type_text = '抢购';
                        $types = 6;
                        if ($orderlists['type'] == 1) {
                            $type_text = '预约';
                            $types = 7;
                        }
                        if ($orderlists['money'] > 0) {
                            $user = (new Users())->where('id', $orderlists['user_id'])->find();
                            (new Users())->MoneyEdit($orderlists['user_id'], $user['money'], $orderlists['money'], 1, $types, $type_text . '合约失败', $orderlists['id']);
                        }
                        (new ContractReser())->where('id', $orderlists['id'])->update(['status' => 3]);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                }
            } else {
                //售卖中的订单
                $selllist = (new ContractSell())->where(['status' => 1, 'product_id' => $lists['id']])->orderRaw('rand()')->order('bixu desc')->select();
                foreach ($selllist as $selllists) {
                    $contractsell = Redis::get('contractsell' . $selllists['id']); //存储库存
                    if ($contractsell) {
                        echo '该卖单匹配中....';
                        continue;
                    }
                    if ($contractsell['bixu'] == 1) {
                        $orderselllist = (new ContractSell())->where(['product_id' => $selllists['id'], 'status' => 1, 'bixu' => 2])->find();
                        if (!empty($orderselllist)) {
                            echo '有必中卖单未匹配完成....';
                            continue;
                        }
                    }
                    Redis::setex('contractsell' . $selllists['id'], 5, 5);
                    $order = (new ContractReser())->where(['cate_id' => $lists['id'], 'status' => 1])->orderRaw('rand()')->find();
                    //如果今日已经有同类匹配订单成功 直接失败
                    $todayorder =  (new ContractReser())->where(['cate_id' => $lists['id'], 'status' => 2, 'user_id' => $order['user_id'], 'dates' => date('Y-m-d')])->find();
                    if (!empty($todayorder) || $order['bixu'] == 3) {
                        Db::startTrans();
                        try {
                            //所有预约之前的订单抢购订单做失败处理
                            $type_text = '抢购';
                            $types = 6;
                            if ($order['type'] == 1) {
                                $type_text = '预约';
                                $types = 7;
                            }
                            if ($order['money'] > 0) {
                                $user = (new Users())->where('id', $order['user_id'])->find();
                                (new Users())->MoneyEdit($order['user_id'], $user['money'], $order['money'], 1, $types, $type_text . '合约失败', $order['id']);
                            }
                            (new ContractReser())->where('id', $order['id'])->update(['status' => 3]);
                            Db::commit();
                        } catch (\Exception $e) {
                            dump($e->getMessage());
                            Db::rollback();
                        }
                    }
                    if ($order['bixu'] == 1) {
                        $orderlist = (new ContractReser())->where(['cate_id' => $lists['id'], 'status' => 1, 'bixu' => 2])->find();
                        if (!empty($orderlist)) {
                            echo '有必中订单未匹配完成....';
                            continue;
                        }
                    }
                    if ($order['user_id'] == $selllists['user_id']) {
                        echo '匹配自己的订单，跳过....';
                        continue;
                    }
                    if (!empty($order)) {
                        $orderlist = Redis::get('contractreser' . $order['id']); //存储库存
                        if ($orderlist) {
                            echo '该买单匹配中....';
                            continue;
                        }
                        Redis::setex('contractreser' . $order['id'], 5, 5);
                        Db::startTrans();
                        try {
                            (new ContractReser())->where('id', $order['id'])->update(['status' => 2, 'sellid' => $selllists['id']]);
                            $id = (new ContractOrder())->insertGetId([
                                'user_id' => $order['user_id'],
                                'seller_id' => $selllists['user_id'],
                                'product_id' => $order['cate_id'],
                                'product_name' => $lists['name'],
                                'matchid' => $selllists['id'],
                                'product_price' => $selllists['price'],
                                'integral' => $order['money'],
                                'price' => $selllists['price'],
                                'maxprice' => $lists['max_price'],
                                'days' => $lists['cycle'],
                                'figure' => $lists['income'],
                                'idays' => $lists['cycle'],
                                'created' => date('Y-m-d H:i:s'),
                                'incometime' =>  date('Y-m-d H:i:s'),
                                'income_status' => 1,
                                'status' => 1
                            ]);
                            (new ContractSell())->where('id', $selllists['id'])->update(['status' => 2, 'toorderid' => $id]);
                            Db::commit();
                        } catch (\Exception $e) {
                            dump($e->getMessage());
                            Db::rollback();
                        }
                        echo '匹配成功';
                    }
                }
            }
        }
    }
}
